package com.whpost.service.service.stamp.h5;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whpost.service.dao.t.THyxxDao;
import com.whpost.service.dao.wx.TWxTokenDao;
import com.whpost.service.dao.wx.TWxUserDao;
import com.whpost.service.entity.t.THyxx;
import com.whpost.service.entity.wx.TWxToken;
import com.whpost.service.entity.wx.TWxUser;
import com.whpost.service.tools.ToolBean;
import com.whpost.service.tools.WxTools;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;


/**
 * (WxToken)表服务实现类
 *
 * @author Yin ZhuoYi
 * @since 2020-12-02 11:02:13
 */
@Service("wxTokenService")


public class WxTokenServiceImpl extends ServiceImpl<TWxTokenDao, TWxToken> {

    @Resource
    private TWxTokenDao tWxTokenDao;
    @Resource
    private WxTools wxTools;
    @Resource
    private TWxUserDao tWxUserDao;
    @Resource
    private THyxxDao tHyxxDao;

    /**
     * 获取token
     * @param appid
     * @param secret
     * @param lx
     * @return
     */
    public String getToken(String appid,String secret,String lx,Long wx_id)
    {
        String token="";
        String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret+"";
        //查询有没有有效的token
        try{
            token = tWxTokenDao.getToken(lx,ToolBean.getToday(),wx_id);
            if (!StringUtils.isEmpty(token))
            {
                ToolBean.info("查询到类型【"+lx+"】的access_token没有过期，直接返回："+token);
                return token;
            }
            else
            {
                ToolBean.info("查询到类型【"+lx+"】的access_token已经过期，需要重新发起get请求来获取！");
                JSONObject jsonObject = wxTools.httpRequest(url,"GET",null);
                if (jsonObject.containsKey("errcode"))
                {
                    ToolBean.info("类型【"+lx+"】的access_token获取失败，错误码："+jsonObject.getString("errcode"));
                    token = "";
                }
                else{

                    token = jsonObject.getString("access_token");
                    String a = jsonObject.getString("expires_in");
                    ToolBean.info("类型【"+lx+"】的access_token获取成功，token："+token);
                    String expires_in = jsonObject.getString("expires_in");
                    ToolBean.info("类型【"+lx+"】的access_token获取成功，token："+token+",准备保存...");
                    tWxTokenDao.delToken(lx,wx_id);
                    tWxTokenDao.saveToken(token,a,lx,ToolBean.getToday(),wx_id);
                    ToolBean.info("类型【"+lx+"】的access_token获取成功，token："+token+",保存成功！");
                }
            }
            return token;
        }
        catch (Exception e)
        {
            ToolBean.info("getToken发生错误！"+e.toString());
            throw new RuntimeException("getToken发生错误！"+e.toString());
        }

    }

    /**
     *
     * @param appid
     * @param secret
     * @param code
     * @return
     */
    public THyxx getOpenidByCode(String appid, String secret, String code)
    {
        String openid="";
        String lx = "2";
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret="+secret+"&code="+code+"&grant_type=authorization_code";

        //查询有没有有效的token
        try{
            JSONObject jsonObject = wxTools.httpRequest(url,"GET",null);
            ToolBean.info("getOpenidByCode返回的数据:"+jsonObject.toString());
            if (jsonObject.containsKey("errcode"))
            {
                ToolBean.info("getOpenidByCode获取失败，错误码："+jsonObject.getString("errcode"));
                openid = "";
                return null;
            }
            else{
                String access_token = jsonObject.getString("access_token");
                openid = jsonObject.getString("openid");
                ToolBean.info("getOpenidByCode获取到openid后去换取其它:"+openid);
                String url1 = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
                JSONObject jsonObject1 = wxTools.httpRequest(url1,"GET",null);
                ToolBean.info("getOpenidByCode获取到openid后去换取其它，返回的数据："+jsonObject1);
                openid = jsonObject1.getString("openid");
                String nickname = jsonObject1.getString("nickname");
                String headimgurl = jsonObject1.getString("headimgurl");
                TWxUser tWxUser = new TWxUser();
                THyxx tHyxx = new THyxx();

                tWxUser = tWxUserDao.selectOne(new QueryWrapper<TWxUser>().eq("openid",openid));

                if (tWxUser!=null){
                    //更新
                    tWxUser.setNickname(nickname);
                    tWxUser.setHeadimgurl(headimgurl);
                    tWxUserDao.updateById(tWxUser);
                }else{
                    tWxUser = new TWxUser();
                    tWxUser.setOpenid(openid);
                    tWxUser.setNickname(nickname);
                    tWxUser.setHeadimgurl(headimgurl);
                    tWxUser.setWxId(1L);    //这里默认都是微信号1
                    tWxUserDao.insert(tWxUser);
                }
                tHyxx = tHyxxDao.selectOne(new QueryWrapper<THyxx>().eq("t_wx_user_lsh",tWxUser.getLsh()));

                if (tHyxx!=null){
                }else{
                    tHyxx = new THyxx();
                    tHyxx.setTel(String.valueOf(tWxUser.getLsh()));
                    tHyxx.setTWxUserLsh(tWxUser.getLsh());
                    tHyxxDao.insert(tHyxx);
                }

                tHyxx = tHyxxDao.selectOne(new QueryWrapper<THyxx>().eq("t_wx_user_lsh",tWxUser.getLsh()));
                return tHyxx;
            }
        }
        catch (Exception e)
        {
            ToolBean.info("getOpenidByCode发生错误！"+e.toString());
            throw new RuntimeException("getOpenidByCode发生错误！"+e.toString());
        }

    }

}